# -*- coding: utf-8 -*-
# @Time    : 2017/7/13 上午 09:04
# @Author  : Aries
# @Site    : 
# @File    : Main.py
# @Software: PyCharm
import hashlib
import random
import string

from flask import *

from bin import common

app = Flask(__name__)
# 32位sessionKey, 每次重启都会更新
app.secret_key = random_str = ''.join([random.choice(string.ascii_letters) for i in range(32)])


@app.route('/')
def index():
    return render_template("index.html",
                           )


# == Account ==
@app.route('/aunt/register', methods=['GET', 'POST'])
def aunt_register():
    if request.method == "POST":
        playername = request.form.get("username")
        email = request.form.get("email")
        password = request.form.get("password")

        # 创建创建玩家对象
        ca = common.Account(
            plyname=playername,
            email=email,
            psw=password,
        )
        # 创建玩家
        uid = ca.add_aunt()
        return "Susses! U uid is:" + str(uid)

    # 默认返回
    return render_template("aunt/register.html",
                           )


@app.route('/aunt/login', methods=['GET', 'POST'])
def aunt_login():
    if request.method == "POST":
        playername = request.form.get("username")
        password = request.form.get("password")

        # 获取UID
        ca = common.Account(plyname=playername)
        print(ca.get_playername_data())
        uid = ca.get_playername_data()['Id']

        # sha256加密密码
        m2 = hashlib.sha256()
        m2.update(password.encode('utf-8'))
        passwd_sha256 = m2.hexdigest()

        # 验证密码
        if passwd_sha256 != ca.get_playername_data()['password']:
            return "Password error!"

        # 登记登录
        common.Account(uid=uid).loggend()

        # 传入session
        session['uid'] = uid
        session['password'] = passwd_sha256

        return "Logged! Valid for 2 hours!"

    # 默认返回
    return render_template("aunt/login.html",
                           )


@app.route('/account')
def user_interface():
    return "You is logged! you can go start your game! Have fun!"

if __name__ == '__main__':
    app.run(host="localhost",
            port=8080,
            debug=True,
            )
